
// out vec4 gl_FragColor;
// in vec2 gl_FragCoord;

#ifdef GL_ES
precision mediump float;
#endif

#define PI 3.1415926535 

uniform vec2 u_resolution;
uniform float u_time;

//画布
vec2 FixUV(vec2 coord,float num){
    //画布原点移动到中央  并且不随外部画布拉伸
    //默认以短轴为基准 num=1.0
    vec2 uv=num*(2.*coord.xy-u_resolution)/
    min(u_resolution.x,u_resolution.y);
    return uv;
}
//网格
vec3 MakeGrid(vec2 uv){
    
    vec3 col=vec3(0.);
    
    vec2 cell=1.-2.*abs(fract(uv)-.5);
    if(cell.x<.01)
    {
        col=vec3(1.);
    }
    if(cell.y<.01)
    {
        col=vec3(1.);
    }
    return col;
    
    // color.r+=step(.98,sin(30.*uv.x));
    // color.r+=step(.98,cos(30.*uv.x));
}
//坐标轴
vec3 MakeAxis(vec2 uv){
    vec3 color=vec3(0.);//
    color.r+=step(-.02,-abs(uv.x));
    color.g+=step(-.02,-abs(uv.y));
    return color;
}

float Segment(in vec2 p,in vec2 a,in vec2 b,in float w){
    
    float f=0.;
    vec2 ba=b-a;
    vec2 pa=p-a;
    float proj=dot(pa,ba)/dot(ba,ba);
    proj=clamp(proj,0.,1.);
    float d=length(proj*ba-pa);;
    // if(d<=w){f=1.;}
    f=step(0.,w-d);
    return f;
}

float FuncSin(in float x){
    float T = 3.+sin(u_time);
    return sin(2.*PI/T*x);
}



float FuncPlot(in vec2 uv){

    float f=0.;
    float resoX=float(u_resolution.x);
    
    for(float x=0.;x<500.;x+=1.){
        float fx=   FixUV(vec2(x,0.),5.).x;
        float nfx=  FixUV(vec2(x+1.,0.),5.).x;

        vec2 fxVec =vec2(fx,FuncSin(fx));
        vec2 nfxVec =vec2(nfx,FuncSin(nfx));
        float funcCurve = Segment(uv,fxVec,nfxVec, 0.02) ; 
        f +=funcCurve;  

    }
    
    return clamp(f,0.,1.);
}

void main(){
    
    vec2 uv=FixUV(gl_FragCoord.xy,5.);
    
    vec3 color=vec3(0.);
    //坐标轴
    color+=MakeAxis(uv);
    //网格
    color+=MakeGrid(uv);
    
    //线段
    float line=Segment(uv,
        vec2(-2.,-4.),
        vec2(2.,2.),
    .03);

    float sincurve =FuncPlot(uv);

    color=mix(color,vec3(1.,1.,0.),line);
    color=mix(color,vec3(1.,1.,0.),sincurve);
    
    gl_FragColor=vec4(color,1.);
    
}